package com.e3.sysmg.security.client;

import java.util.List;

import com.e3.sysmg.security.model.UserModel;
import com.e3.sysmg.security.model.UserStatus;
import com.e3.web.core.client.EditorListener;
import com.e3.web.core.client.GXTHelper;
import com.e3.web.core.client.GridListener;
import com.e3.web.core.client.GwtAsyncCallback;
import com.e3.web.core.client.QueryListener;
import com.e3.web.core.model.SuperQC;
import com.e3.web.widget.client.BaseAction;
import com.e3.web.widget.client.MyButton;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.user.client.Element;
/**
 * User管理主界面采用上下两个grid的方式进行显示。
 * 上边显示User的查询结果，下边显示User所属的角色。
 * 当双击或编辑某个User时，弹出编辑对话框。
 * 编辑对话框以form形式显示。分成两个部分，一部分是基本信息，一部分是所属的角色。
 * 角色所属信息用grid显示，可以查看角色所拥有的模块。
 * 也可以查看用户所拥有的所有模块。
 * @author Janty
 *
 */
public class UserUI extends LayoutContainer implements QueryListener<UserModel>,EditorListener<UserModel>,GridListener<UserModel>{
	
	private UserRPCServiceAsync service = UserRPCService.Util.getInstance();
	private UserMessages MESSAGES = UserMessages.INSTANCE;
	
	private MyButton queryButton = new MyButton(UserStateMachine.QUERY_ACTION);
	private MyButton newButton = new MyButton(UserStateMachine.NEW_ACTION);
	private MyButton modifyButton = new MyButton(UserStateMachine.MODIFY_ACTION);
	private MyButton deleteButton = new MyButton(UserStateMachine.DELETE_ACTION);

	private UserGridPanel userGridPanel;
	
	private UserRoleGridPanel roleGridPanel;
	
	private UserQueryDialog queryDialog;
	
	private UserEditorDialog editorDialog;
	
	private ContentPanel contentPanel = new ContentPanel(new BorderLayout());
	
	private ToolBar toolbar = new ToolBar();
	
	private SelectionListener<ButtonEvent> btnSelectListener = new SelectionListener<ButtonEvent>() {
		@Override
		public void componentSelected(ButtonEvent ce) {
			MyButton item = (MyButton)ce.getSource();
			onBtnMnuEvent(item.getAction());
		}
	};
	
//	private SelectionListener<MenuEvent> mnuSelectListener = new SelectionListener<MenuEvent>() {
//		@Override
//		public void componentSelected(MenuEvent ce) {
//			ce.getSource();
//			MyMenuItem item = (MyMenuItem)ce.getItem();
//			onBtnMnuEvent(item.getAction());
//		}
//	};
	
	private Listener<MessageBoxEvent> msgBoxListener = new Listener<MessageBoxEvent>(){

		public void handleEvent(MessageBoxEvent be) {
			Button btn = be.getButtonClicked();
			onMessageBoxButton(btn);
		}
		
	};
	
	@Override
	protected void onRender(Element parent, int index) {
		super.onRender(parent, index);
		setLayout(new FitLayout());
		
		BorderLayoutData bld = new BorderLayoutData(LayoutRegion.NORTH);
		bld.setSplit(true);
		bld.setMargins(new Margins(0,2,0,0));
		contentPanel.add(getUserGridPanel(),bld);
		
		bld = new BorderLayoutData(LayoutRegion.CENTER);
		ContentPanel prolePanel = new ContentPanel(new FitLayout());
		prolePanel.add(getUserRoleGridPanel());
		prolePanel.setHeading(MESSAGES.title_parent_roles());
		contentPanel.add(prolePanel,bld);
		
		initToolBar();
		contentPanel.setTopComponent(toolbar);
		
		contentPanel.setHeaderVisible(false);
		add(contentPanel);
	}
	
	private UserGridPanel getUserGridPanel(){
		if(userGridPanel == null){
			userGridPanel = new UserGridPanel();
			userGridPanel.addGridListener(this);
		}
		return userGridPanel;
	}
	
	private UserRoleGridPanel getUserRoleGridPanel(){
		if(roleGridPanel == null){
			roleGridPanel = new UserRoleGridPanel();
		}
		return roleGridPanel;
	}
	
	private UserQueryDialog getUserQueryDialog(){
		if(queryDialog == null){
			queryDialog = new UserQueryDialog();
			queryDialog.addQueryListener(this);
		}
		return queryDialog;
	}
	
	private UserEditorDialog getUserEditorDialog(){
		if(editorDialog == null){
			editorDialog = new UserEditorDialog();
			editorDialog.addEditorListeners(this);
		}
		return editorDialog;
	}

	private void initToolBar(){
		queryButton.addSelectionListener(btnSelectListener);
		toolbar.add(queryButton);
		newButton.addSelectionListener(btnSelectListener);
		toolbar.add(newButton);
		
		modifyButton.addSelectionListener(btnSelectListener);
		toolbar.add(modifyButton);
		deleteButton.addSelectionListener(btnSelectListener);
		toolbar.add(deleteButton);
		
	}
	
	private void onBtnMnuEvent(BaseAction action){
		if(action == UserStateMachine.QUERY_ACTION){
			onQuery();
		}
		else if(action == UserStateMachine.NEW_ACTION){
			onNew();
		}
		else if(action == UserStateMachine.MODIFY_ACTION){
			onModify();
		}
		else if(action == UserStateMachine.DELETE_ACTION){
			onDelete();
		}
	}

	private void onDelete() {
		List<UserModel> models = getUserGridPanel().getSelectedUsers();
		if(models == null||models.size()==0){
			MessageBox.alert(MESSAGES.msgbox_alert_title(), MESSAGES.msg_delete_info(MESSAGES.local_name()), null);
			return;
		}
		StringBuffer msgs = new StringBuffer();
		String localName = MESSAGES.local_name();
		for (UserModel userModel : models) {
			String code = UserHelper.INSTANCE.getFieldDisplayName(UserModel.CODE);
			String name = UserHelper.INSTANCE.getFieldDisplayName(UserModel.NAME);
			msgs.append(code+"="+userModel.getCode()+","+name+"="+userModel.getName()+";\n");
		}
		MessageBox.confirm(MESSAGES.msgbox_confirm_delete_title(), MESSAGES.msg_delete_confirm(localName, msgs.toString()), msgBoxListener);

	}

	private void onModify() {
		List<UserModel> values = getUserGridPanel().getSelectedUsers();
		if(values==null||values.isEmpty()){
			MessageBox.alert(MESSAGES.msgbox_alert_title(),MESSAGES.msg_modify_info(MESSAGES.local_name()), null);
			return;
		}
		getUserEditorDialog().showDialog(values.get(0), false);
	}

	private void onNew() {
		UserModel model = new UserModel();
		model.setStatus(UserStatus.STATUS_NORMAL+"");
		getUserEditorDialog().showDialog(model,true);
	}

	private void onQuery() {
		getUserQueryDialog().setVisible(true);
	}
	
	private void onMessageBoxButton(Button btn) {
		if ("yes".equals(btn.getItemId())) {
			GXTHelper.maskDelete(this);

			final List<UserModel> userModels = getUserGridPanel().getSelectedUsers();
			service.deleterUsers(userModels, new GwtAsyncCallback<Void>(this) {
				@Override
				public void doSuccess(Void result) {
					getUserGridPanel().removeDatas(userModels);
					int count = getUserGridPanel().getGridStore().getCount();
					UserModel model = null;
					if(count > 0){
						model = getUserGridPanel().getGridStore().getAt(0);
					}
					onGridSelectionChanged(model);
				}
			});
		}
	}

	public void onGridSelectionChanged(UserModel model) {
		List<UserModel> userModels = getUserGridPanel().getSelectedUsers();
		if(userModels!=null&&userModels.size()>0){
			UserModel userModel = userModels.get(0);
			getUserRoleGridPanel().setGridValues(userModel.getRoles());
		}
	}

	public void onGridRowDoubClicked(UserModel model) {
		onModify();
	}

	public void onEditSuccess(UserModel model) {
		getUserGridPanel().refreshGridData(model);
	}

	public void onQuerySuccessed(SuperQC qc,List<UserModel> results) {
		getUserGridPanel().setGridValues(results);
	}

}
